package com.example.seh.util;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.webkit.MimeTypeMap;

import androidx.annotation.RequiresApi;

import org.apache.commons.io.FileUtils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ImgUtil {
    //压缩图片
    public static Bitmap scaleBitmap(Bitmap origin, float ratio) {
        if (origin == null) {
            return null;
        }
        int width = origin.getWidth();
        int height = origin.getHeight();
        Matrix matrix = new Matrix();
        matrix.preScale(ratio, ratio);
        Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
        return newBM;
    }

    public static Bitmap setUserAvatar(String str) throws IOException {
        return ImgUtil.scaleBitmap(ImgUtil.toRoundBitmap(ImgUtil.stringToBitmap(str)), 0.5f);
    }

    public static Bitmap setDefaultAvatar(Context context, int str) throws IOException {
        return ImgUtil.scaleBitmap(ImgUtil.toRoundBitmap(ImgUtil.intToBitmap(context, str)), 0.5f);
    }

    public static Bitmap intToBitmap(Context context, int item) {
        Drawable drawable = context.getResources().getDrawable(item);
        BitmapDrawable bd = (BitmapDrawable) drawable;
        Bitmap bmm = bd.getBitmap();
        return bmm;
    }

    public static Bitmap stringToBitmap(String path) throws IOException {
        InputStream inputStream = null;
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            if (conn.getResponseCode() == 200) {
                inputStream = conn.getInputStream();
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                return bitmap;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
            }
        }

        return null;
    }
    public static Bitmap toRoundBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float roundPx;
        float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
        if (width <= height) {
            roundPx = width / 2;
            left = 0;
            top = 0;
            right = width;
            bottom = width;
            height = width;
            dst_left = 0;
            dst_top = 0;
            dst_right = width;
            dst_bottom = width;
        } else {
            roundPx = height / 2;
            float clip = (width - height) / 2;
            left = clip;
            right = width - clip;
            top = 0;
            bottom = height;
            width = height;
            dst_left = 0;
            dst_top = 0;
            dst_right = height;
            dst_bottom = height;
        }

        Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom);
        final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom);
        final RectF rectF = new RectF(dst);

        paint.setAntiAlias(true);// 设置画笔无锯齿

        canvas.drawARGB(0, 0, 0, 0); // 填充整个Canvas
        paint.setColor(color);

        // 以下有两种方法画圆,drawRounRect和drawCircle
        // canvas.drawRoundRect(rectF, roundPx, roundPx, paint);// 画圆角矩形，第一个参数为图形显示区域，第二个参数和第三个参数分别是水平圆角半径和垂直圆角半径。
        canvas.drawCircle(roundPx, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));// 设置两张图片相交时的模式,参考http://trylovecatch.iteye.com/blog/1189452
        canvas.drawBitmap(bitmap, src, dst, paint); //以Mode.SRC_IN模式合并bitmap和已经draw了的Circle

        return scaleBitmap(output, 0.5f);
    }

    public static File uriToFile(Uri uri, Context context) {
        String filePath = null;
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            if (inputStream != null) {
                File cacheDir = context.getCacheDir();
                File tempFile = File.createTempFile("image", null, cacheDir);
                tempFile.deleteOnExit();
                String tempFilePath = tempFile.getAbsolutePath();
                FileUtils.copyInputStreamToFile(inputStream, tempFile);
                filePath = tempFilePath;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        File file = new File(filePath);
        return file;
    }

    public static boolean isImg(String str) {
        boolean isimg = false;
        if (str.length() >= 24) {
            String s1 = str.substring(7).substring(0, str.substring(7).indexOf(":"));
            String s2 = str.substring(str.length()-4, str.length());
            if (isIP(s1) && ".png".equals(s2)) {
                isimg = true;
            }
        }
        return isimg;
    }
    /**
     * 判断一个字符串是否是一个合法的ip地址：
     *    1 首先检查字符串的长度 最短应该是0.0.0.0 7位 最长 000.000.000.000 15位
     *    2 按.符号进行拆分，拆分结果应该是4段
     *    3 检查每个字符串是不是都是数字
     */
    public static boolean isIP(String str){
        // 1、首先检查字符串的长度 最短应该是0.0.0.0 7位 最长 000.000.000.000 15位
        if(str.length()<7 || str.length() >15) return false;
        // 2、按.符号进行拆分，拆分结果应该是4段，"."、"|"、"^"等特殊字符必须用 \ 来进行转义
        // 而在java字符串中，\ 也是个已经被使用的特殊符号，也需要使用 \ 来转义
        String[] arr = str.split("\\.");
        if( arr.length != 4 )    return false;
        // 3、检查每个字符串是不是都是数字,ip地址每一段都是0-255的范围
        for(int i = 0 ; i <4 ; i++ ){
            if (!isNUM(arr[i]) || arr[i].length()==0 || Integer.parseInt(arr[i])>255 || Integer.parseInt(arr[i])<0){
                return false;
            }
        }
        return true;
    }

    /**
     * 判断一个字符串是否是数字
     */
    static boolean isNUM(String str){
        Pattern p = Pattern.compile("[0-9]*");
        Matcher m = p.matcher(str);
        return m.matches();
    }
}
